package com.kly.cashmall.module.login;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gyf.immersionbar.ImmersionBar;
import com.kly.cashmall.R;
import com.kly.cashmall.base.BaseBarActivity;
import com.kly.cashmall.base.app_action.ActionHeads;
import com.kly.cashmall.base.app_action.BaseActionHelper;
import com.kly.cashmall.bean.LoginBean;
import com.kly.cashmall.bean.ProtocolBean;
import com.kly.cashmall.framework.mvp.PresenterLifeCycle;
import com.kly.cashmall.module.login.presenter.LoginPresenter;
import com.kly.cashmall.module.login.presenter.LoginViewer;
import com.kly.cashmall.module.web.WebViewActivity;
import com.kly.cashmall.services.UserInfoHelper;
import com.kly.cashmall.utils.function.ToastUtil;
import com.kly.cashmall.widget.delay.ClickPreventableTextView;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * @author
 */
public class LoginActivity extends BaseBarActivity implements LoginViewer, View.OnClickListener {

    /**
     * 标志是否存在，存在时候重新启动，主要用于单点登录
     */
    public static boolean pFlag = false;

    @PresenterLifeCycle
    LoginPresenter presenter = new LoginPresenter(this);
    private EditText mEditCode;
    private EditText mEditMobile;
    private Button mBtnLogin;
    private TextView mUserRegisterAgreement;
    private TextView mSendVerCode;
    public static final int MOBILE_LENGTH = 10;
    public static final int CODE_LENGTH = 5;

    public static final int PROTOCOL_TERMS_AND_CONDITIONS = 1;
    public static final int PROTOCOL_PRIVACY_POLICY = 2;
    private int type;

    public static Intent callIntent(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        return intent;
    }

    public static Intent callIntent(Context context, int type) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra("type", type);
        return intent;
    }

    /**
     * 跳转客服之类的
     * 不能在登录情况下调用
     */
    public static Intent callRedirectOtherActionIntent(Context context, String targetOther, @Nullable Bundle bundle) {
        return LoginRedirectHelper.setRedirectData(context, LoginActivity.class, bundle, "", targetOther);
    }

    @Override
    protected void setView(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        setTitle("");
        setIcon(R.mipmap.ic_black_close);

        setToolbarBackgroundColor(Color.WHITE);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
        type = getIntent().getIntExtra("type", -1);

        mEditCode = bindView(R.id.edit_code);
        mEditMobile = bindView(R.id.edit_mobile);
        mBtnLogin = bindView(R.id.btn_login, this);
        mUserRegisterAgreement = bindView(R.id.user_register_agreement);
        mSendVerCode = bindView(R.id.send_ver_code, this);
        initEvent();

        mBtnLogin.setText("Log In");
        bindView(R.id.top_one, true);
        bindView(R.id.top_two, false);


    }

    private void initEvent() {
        String registerAgreement = getString(R.string.all_register_agreement);
        String termsConditions = getString(R.string.login_terms_conditions);
        String termsConditionsTwo = getString(R.string.privacy_policy);
        int oneStart = registerAgreement.indexOf(termsConditions);
        int oneEnd = oneStart + termsConditions.length();

        int twoStart = registerAgreement.indexOf(termsConditionsTwo);
        int twoEnd = twoStart + termsConditionsTwo.length();
        SpannableString spannable = new SpannableString(registerAgreement);
        spannable.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NotNull View widget) {

                if (widget instanceof ClickPreventableTextView) {
                    if (((ClickPreventableTextView) widget).ignoreSpannableClick()) {
                        return;
                    }
                    ((ClickPreventableTextView) widget).preventNextClick();
                }

                presenter.getProtocol(PROTOCOL_TERMS_AND_CONDITIONS);
            }
        }, oneStart, oneEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannable.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NotNull View widget) {

                if (widget instanceof ClickPreventableTextView) {
                    if (((ClickPreventableTextView) widget).ignoreSpannableClick()) {
                        return;
                    }
                    ((ClickPreventableTextView) widget).preventNextClick();
                }

                presenter.getProtocol(PROTOCOL_PRIVACY_POLICY);
            }
        }, twoStart, twoEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mUserRegisterAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        mUserRegisterAgreement.setText(spannable);


        mEditMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mSendVerCode.setEnabled(s.length() >= MOBILE_LENGTH);
            }
        });
        mEditCode.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mEditMobile.length() > 0 && s.length() >= CODE_LENGTH) {
                    mBtnLogin.setEnabled(true);
                } else {
                    mBtnLogin.setEnabled(false);
                }
            }
        });
    }

    @Override
    protected void loadData() {

    }

    @Override
    public void getVerifycodeSendSuccess(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void getLoginVerifycodeFail(String errorMsg) {
        ToastUtil.showToast(errorMsg);
    }

    @Override
    public void setResult() {
        setResult(RESULT_OK);
    }

    @Override
    public Bundle getLoginExtraBundle() {
        return LoginRedirectHelper.getLoginExtraBundle(getActivity());
    }

    @Override
    public String getRedirectActivityClassName() {
        return LoginRedirectHelper.getRedirectActivityClassName(getActivity());
    }

    @Override
    public String getRedirectOtherAction() {
        return LoginRedirectHelper.getRedirectOtherAction(getActivity());
    }

    @Override
    public void getProtocolSuccess(int type, ProtocolBean bean) {
        if (null != bean) {
            if (type == PROTOCOL_TERMS_AND_CONDITIONS) {
                String registerProtocol = bean.getRegisterProtocol();
                startActivity(WebViewActivity.callIntent(this, getString(R.string.login_terms_conditions),
                        registerProtocol));
            }
            if (type == PROTOCOL_PRIVACY_POLICY) {
                String privacyPolicy = bean.getPrivacyPolicy();
                startActivity(WebViewActivity.callIntent(this, getString(R.string.privacy_policy),
                        privacyPolicy));
            }
        }
    }

    @Override
    public void getSocialBindMobileSuccess(LoginBean bean) {
        UserInfoHelper.getInstance().setToken(bean.getToken());
        BaseActionHelper.with(getActivity()).handleAction(ActionHeads.LMActionHome);
        finish();
    }

    @Override
    public void onClick(View view) {
        String mobile = mEditMobile.getText().toString();
        switch (view.getId()) {
            case R.id.send_ver_code:
                if (mobile.length() >= 10) {
                    presenter.getVerifycodeSend(mobile);
                    Observable.interval(1, TimeUnit.SECONDS)
                            .take(90)
                            .map(new Function<Long, Long>() {
                                @Override
                                public Long apply(Long v) throws Exception {
                                    return 90 - v;
                                }
                            })
                            .subscribeOn(Schedulers.computation())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<Long>() {
                                @Override
                                public void onSubscribe(@NonNull Disposable d) {
                                }

                                @Override
                                public void onNext(@NonNull Long aLong) {
                                    bindText(R.id.send_ver_code, aLong + "s");
                                    bindEnable(R.id.send_ver_code, false);

                                }

                                @Override
                                public void onError(@NonNull Throwable e) {

                                }

                                @Override
                                public void onComplete() {
                                    bindText(R.id.send_ver_code, getString(R.string.all_get_verification_code));
                                    bindEnable(R.id.send_ver_code, true);
                                }
                            });
                } else {
                    ToastUtil.showToast(getString(R.string.correct_phone));
                }

                break;
            case R.id.btn_login:
                if (mobile.length() >= 10) {
                    presenter.getLoginVerifycode(mEditMobile.getText().toString(), mEditCode.getText().toString());
                } else {
                    ToastUtil.showToast(getString(R.string.correct_phone));
                }
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
